package org.springblade.modules.mes.unit.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.mp.TenantEntity;
import org.springblade.modules.mes.unit.entity.UnitEntity;
import org.springblade.modules.mes.unit.mapper.UnitMapper;
import org.springblade.modules.mes.unit.service.IUnitService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 计量单位
 * @author zhanglianchao
 */
@Service("unitService")
public class UnitServiceImpl extends BaseServiceImpl<UnitMapper, UnitEntity> implements IUnitService {

    /**
     * 数据编码唯一性校验
     * @param code 编码
     * @param id 更新时的id
     * @return 校验结果 true 已存在 false 未存在
     */
    @Override
    public boolean countByCode(String code, Long id) {
        int counts = this.baseMapper.countByCode(code,id, AuthUtil.getTenantId());
        return counts > 0;
    }

    /**
     * 设置默认单位
     * @param id 要设置的计量单位id
     * @return 设置结果
     */
    @Transactional
    @Override
    public boolean setDefault(Long id) {
        //设置为非默认
        this.baseMapper.setNoDefault();
        //设置默认单位
        this.baseMapper.setDefault(id);
        return true;
    }

    /**
    *  按编码取一个单位详情
    * @author 翁金川
    *  2021/3/10 19:00
    * @Param [code]
    * @return org.springblade.base.entity.unit.UnitEntity
    */
    @Override
    @Cacheable(value = "unit:Code", key = "#code", unless="#result == null")
    public UnitEntity getByCode(String code) {
        QueryWrapper<UnitEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(UnitEntity::getCode,code).eq(TenantEntity::getTenantId,AuthUtil.getTenantId());

        return this.getOne(queryWrapper);
    }
}
